using System;
using System.Configuration;
using System.Data.Entity;
using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using FluentValidation.Mvc;
using PhoneBook.Controllers;
using PhoneBook.Core.Data;
using PhoneBook.Core.Infrastructure;
using PhoneBook.Core.Infrastructure.DependencyManagement;
using PhoneBook.Data;
using PhoneBook.Service.Contacts;
using PhoneBook.Service.UserGroups;

namespace PhoneBook
{
    public class PbEngine : IEngine
    {


        private ContainerManager _containerManager;


        public ContainerManager ContainerManager
        {
            get { return _containerManager; }
        }


        public PbEngine()
        {
          

        }
     


        public void Initialize()
        {
            //var connstr = ConfigurationManager.ConnectionStrings["pbConnectionString"].ToString();
            var builder = new ContainerBuilder();

            //db
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest();
            builder.Register<DbContext>(c => new PbContext()).InstancePerHttpRequest();


            //service
            builder.RegisterType<ContactService>().As<IContactService>();
            builder.RegisterType<UserGroupService>().As<IUserGroupService>();


            //controller
            builder.RegisterControllers(Assembly.GetExecutingAssembly());


            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            
            _containerManager = new ContainerManager(container);

            FluentValidationModelValidatorProvider.Configure();

            AutoMapperConfigure.Configure();
        }

        public T Resolve<T>() where T : class
        {
            return ContainerManager.Resolve<T>();
        }

        public object Resolve(Type type)
        {
            return ContainerManager.Resolve(type);
        }

        public T[] ResolveAll<T>()
        {
            return ContainerManager.ResolveAll<T>();
        }
    }
}